package com.software.twinmanager.controller;

import com.software.twinmanager.tcp.TCPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@ServerEndpoint("/message/{name}")
public class MessageReceiver {
    private Session session; //与某个客户端的连接对话，通过它对客户端发送消息
    private String name; //标识当前连接客户端的用户名
    public static final ConcurrentHashMap<String, MessageReceiver> webSocketSet = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "name") String name) {
        this.session = session;
        this.name = name;
        webSocketSet.put(name, this);
        log.info("[WebSocket] " + name + "已经连接至服务端");
    }

    @OnClose
    public void onClose() {
        log.info("[WebSocket] " + name + "已经断开服务端");
        webSocketSet.remove(this.name);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.warn("[WebSocket] " + name + "发生错误");
    }

    @OnMessage
    public void onMessage(byte[] message) {
        log.info("[WebSocket] 服务端接收" + name + "消息：" + Arrays.toString(message));
        if (name.equals("client")) {
            TCPUtils.sendCommand(message);
        }
        else if (name.equals("server")) {
            ByteBuffer buffer = ByteBuffer.allocate(message.length);
            buffer.put(message);
            appointSending("client", buffer);
        }
    }

    public void groupSending(String message) {
        for (String name : webSocketSet.keySet()) {
            try {
                webSocketSet.get(name).session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                log.warn("[WebSocket] 群发出错");
                e.printStackTrace();
            }
        }
    }

    public void appointSending(String name, String message) {
        try {
            webSocketSet.get(name).session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.warn("[WebSocket] 单发出错");
            e.printStackTrace();
        }
    }public void appointSending(String name, ByteBuffer buffer) {
        try {
            webSocketSet.get(name).session.getBasicRemote().sendBinary(buffer);
        } catch (Exception e) {
            log.warn("[WebSocket] 单发出错");
            e.printStackTrace();
        }
    }
}
